<template>
  <div class="rights-manage">
    <div class="nav-wrapper" v-show="showNav">
      <router-link
        v-for="{ routerName, label, icon } in navList"
        :key="routerName"
        :to="{ name: routerName }"
        class="nav-item"
      >
        <i :class="icon"></i>
        {{ label }}
      </router-link>
    </div>
    <div class="router-view">
      <router-view v-slot="{ Component }">
        <keep-alive include="MemberList">
          <component :is="Component" />
        </keep-alive>
      </router-view>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex';

export default {
  computed: {
    ...mapGetters('user', ['isSuperAdmin', 'userPermission', 'getChildMenusByRouteName']),
    ...mapState('user', ['menuTree']),
    showNav() {
      return !['addMember', 'addRole'].includes(this.$route.name);
    },
    showRoleManage() {
      return this.isSuperAdmin || this.userPermission.level < 4;
    },
    // 从菜单数据中获取子菜单并转换为 navList 格式
    navList() {
      // 始终使用 'rightsManage' 作为父路由名称来获取子菜单
      // 因为当前路由可能是子路由（如 memberList），我们需要获取父路由的子菜单
      const parentRouteName = 'rightsManage';
      
      // 从菜单树中获取子菜单
      const childMenus = this.getChildMenusByRouteName(parentRouteName);
      
      console.log('RightsManage navList: 父路由名称:', parentRouteName);
      console.log('RightsManage navList: 获取到的子菜单:', childMenus);
      console.log('RightsManage navList: 当前路由名称:', this.$route.name);
      
      // 转换为 navList 格式
      let navList = childMenus.map(menu => {
        // 从 menu_path 中提取路由名称
        const menuPath = menu.menu_path || '';
        let routerName = '';
        if (menuPath) {
          const pathParts = menuPath.split('/').filter(part => part && part !== 'homepage');
          if (pathParts.length > 0) {
            routerName = pathParts[pathParts.length - 1];
          }
        }
        
        return {
          label: menu.menu_name || '',
          routerName: routerName,
          icon: menu.menu_icon || 'el-icon-menu'
        };
      }).filter(item => item.routerName); // 过滤掉没有路由名称的项
      
      // 根据权限过滤
      if (!this.showRoleManage) {
        navList = navList.filter((e) => e.label !== '角色管理');
      }
      
      console.log('RightsManage navList: 转换后的导航列表:', navList);
      console.log('RightsManage navList: 导航列表长度:', navList.length);
      return navList;
    },
  },
  async mounted() {
    // 检查子菜单是否存在，如果不存在则获取
    await this.ensureChildMenusLoaded();
    
    // 如果当前路由是父路由（rightsManage）且没有子路由显示，自动跳转到第一个子路由
    if (this.$route.name === 'rightsManage' && this.navList.length > 0) {
      const firstChildRoute = this.navList[0];
      if (firstChildRoute && firstChildRoute.routerName) {
        console.log('RightsManage: 检测到父路由，自动跳转到第一个子路由:', firstChildRoute.routerName);
        this.$router.replace({ name: firstChildRoute.routerName }).catch(err => {
          // 忽略重复导航错误
          if (err.name !== 'NavigationDuplicated') {
            console.error('RightsManage: 跳转到子路由失败', err);
          }
        });
      }
    }
  },
  watch: {
    // 监听路由变化，确保子菜单已加载
    '$route': {
      handler: async function() {
        await this.ensureChildMenusLoaded();
      },
      immediate: false
    },
    // 监听菜单树变化，确保子导航能响应更新
    menuTree: {
      handler(newVal, oldVal) {
        console.log('RightsManage: menuTree 变化', {
          oldLength: oldVal?.length || 0,
          newLength: newVal?.length || 0,
          hasRightsManage: newVal?.some(m => m.menu_path?.includes('rightsManage')) || false
        });
        // 检查校务管理菜单是否有子菜单
        const rightsManageMenu = newVal?.find(m => {
          const path = m.menu_path || '';
          return path.includes('rightsManage') && !path.includes('rightsManage/');
        });
        if (rightsManageMenu) {
          console.log('RightsManage: 找到校务管理菜单，children 数量:', rightsManageMenu.children?.length || 0);
        }
        // 强制更新组件，确保 navList 重新计算
        this.$nextTick(() => {
          console.log('RightsManage: 强制更新组件，当前 navList 长度:', this.navList.length);
          this.$forceUpdate();
        });
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 确保子菜单已加载
    async ensureChildMenusLoaded() {
      const currentRouteName = this.$route.name;
      if (!currentRouteName || currentRouteName === 'rightsManage') {
        // 获取当前菜单的子菜单
        const childMenus = this.getChildMenusByRouteName('rightsManage');
        
        // 如果子菜单为空，尝试从菜单树中查找父菜单并获取子菜单
        if (!childMenus || childMenus.length === 0) {
          const menuTree = this.menuTree || [];
          const findMenu = (menus, targetName) => {
            for (const menu of menus) {
              const menuPath = menu.menu_path || '';
              if (menuPath) {
                const pathParts = menuPath.split('/').filter(part => part && part !== 'homepage');
                if (pathParts.length > 0 && pathParts[pathParts.length - 1] === targetName) {
                  return menu;
                }
              }
              if (menu.children && Array.isArray(menu.children) && menu.children.length > 0) {
                const found = findMenu(menu.children, targetName);
                if (found) return found;
              }
            }
            return null;
          };
          
          // 登录时已经通过 fetchAllButtonPermissions 获取了完整的菜单树（包含所有子菜单和按钮）
          // 所以这里不需要再调用 fetchMenuChildren
          const parentMenu = findMenu(menuTree, 'rightsManage');
          if (parentMenu) {
            const hasChildren = parentMenu.children && 
                              Array.isArray(parentMenu.children) && 
                              parentMenu.children.some(child => child.menu_type === 1);
            console.log('RightsManage: 菜单子菜单状态:', hasChildren ? '已有子菜单' : '无子菜单');
          }
        }
      }
    }
  }
};
</script>

<style lang="less" scoped>
.rights-manage {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 24px;
  position: relative;
  background-color: #f5f7fa;
  
  .nav-wrapper {
    display: flex;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    padding: 0 20px;
    margin-bottom: 20px;
    
    .nav-item {
      height: 56px;
      line-height: 56px;
      color: rgba(0, 0, 0, 0.7);
      margin-right: 40px;
      font-size: 15px;
      transition: all 0.3s;
      display: flex;
      align-items: center;
      
      i {
        margin-right: 8px;
        font-size: 18px;
      }
      
      &:last-child {
        margin-right: 0;
      }
      
      &:hover {
        color: #009cff;
      }
    }
    
    .router-link-active {
      color: #009cff;
      font-weight: bold;
      position: relative;
      
      &::after {
        content: '';
        display: block;
        width: 50%;
        height: 3px;
        background-color: #009cff;
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        border-radius: 3px 3px 0 0;
      }
    }
  }
  
  .router-view {
    flex: 1;
    overflow-y: auto;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    padding: 20px;
  }
}
</style>
